package cn.moukou.sbzz.service;

import cn.moukou.sbzz.mapper.EnterpriseMapper;
import cn.moukou.sbzz.pojo.Enterprise;
import cn.moukou.sbzz.util.JwtUtil;
import cn.moukou.sbzz.util.Md5Util;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class EnterpriseService {
    @Autowired
    EnterpriseMapper enterpriseMapper;

    public Enterprise enterpriseLogin(String username, String pwd) throws Exception {
        Enterprise enterprise = enterpriseMapper.selectById(username);
        if(enterprise == null) {
            return null;
        }

        if (Md5Util.getMD5String(pwd).equals(enterprise.getPwd())) {
            Map<String, Object> tokenMap = new HashMap<>();
            tokenMap.put("uid", username);
            tokenMap.put("role", "enterprise");
            String token = JwtUtil.generateToken(tokenMap, 6000);
            enterprise.setPwd(token);
            return enterprise;
        } else {
            return null;
        }
    }

    public List<Enterprise> getEnterpriseList() {
        return enterpriseMapper.selectList(null);
    }

    public List<Enterprise> getEnterpriseToAuth() {
        QueryWrapper<Enterprise> wrapper = new QueryWrapper<>();
        wrapper.eq("auth", 1);
        return enterpriseMapper.selectList(wrapper);
    }

    public int authEnterprise(String id) {
        Enterprise enterprise = enterpriseMapper.selectById(id);
        if(enterprise == null) {
            return 0;
        }
        enterprise.setAuth(2);
        return enterpriseMapper.updateById(enterprise);
    }

    public int submitEnterprise(String id, String name, String detail, String link) {
        Enterprise enterprise = enterpriseMapper.selectById(id);
        enterprise.setName(name);
        enterprise.setDetail(detail);
        enterprise.setLink(link);
        enterprise.setAuth(1);
        return enterpriseMapper.updateById(enterprise);
    }

    public int accessEnterprise(String id, String form, String business, String pool) {
        Enterprise enterprise = enterpriseMapper.selectById(id);
        if(enterprise == null) {
            return 0;
        }
        enterprise.setFormAccess(form);
        enterprise.setBusinessAccess(business);
        enterprise.setPoolAccess(pool);
        return enterpriseMapper.updateById(enterprise);
    }

    public Enterprise getOneEnterprise(String id) {
        return enterpriseMapper.selectById(id);
    }

}
